const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const CDPClient = require('./cdp-client');

let cdpClient = null;

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      devTools: true,
      enableRemoteModule: true
    }
  });

  mainWindow.loadFile('src/index.html');
  mainWindow.webContents.openDevTools();

  // 初始化CDP客户端
  cdpClient = new CDPClient('localhost', 9229, {
    maxRetries: 3,
    retryDelay: 1000,
    onRetry: (retries, maxRetries) => {
      console.log(`[Debug] 连接失败，正在进行第${retries}/${maxRetries}次重试...`);
    }
  });

  // 设置消息处理器
  cdpClient.onMessage(message => {
    console.log('[Debug] 主进程收到CDP消息:', JSON.stringify(message, null, 2));
    mainWindow.webContents.send('cdp-message', message);
  });

  cdpClient.onError(error => {
    console.error('[Error]', error.message, '\n', error.stack);
  });

  // 自动连接到调试目标
  connectToTarget();
}

async function connectToTarget() {
  try {
    await cdpClient.connect();
    console.log('[Debug] Successfully connected to debug target');
  } catch (err) {
    console.error('[Error] Connection failed:', err.message);
    // Set reconnection timer
    setTimeout(connectToTarget, 5000);
  }
}

app.whenReady().then(() => {
  createWindow();

  // 监听调试消息
  ipcMain.on('debug-message', (event, message) => {
    console.log('[Debug]', typeof message === 'string' ? message : JSON.stringify(message, null, 2));
  });

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', function () {
  if (cdpClient) {
    clearTimeout(global.reconnectTimer); // 清除重连定时器
    cdpClient.disconnect();
    cdpClient = null;
  }
  if (process.platform !== 'darwin') app.quit();
});